package com.jinyang.baserouter.serialization

import android.content.Context
import android.util.LruCache
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.facade.service.SerializationService
import com.jinyang.baserouter.log
import java.lang.reflect.Type
import java.util.*


/**
 * @Author:         LiuJinYang
 * @CreateDate:     2021/12/8
 * @Description:
 */
//@Route(path = "/serialization/lruCache")
class LruCacheSerializationServiceImpl : SerializationService {
    private val lruCache by lazy {
        val maxMemory = Runtime.getRuntime().maxMemory()
        val cacheSize = (maxMemory / 8).toInt()
        LruCache<String, Any>(cacheSize)
    }

    override fun init(context: Context) {
        log("LruCacheSerializationServiceImpl.init")

    }

    override fun object2Json(instance: Any): String {
        log("LruCacheSerializationServiceImpl.object2Json")
        val uuid = UUID.randomUUID().toString()
        lruCache.put(uuid, instance)
        return uuid
    }

    override fun <T : Any> json2Object(input: String, clazz: Class<T>): T {
        log("LruCacheSerializationServiceImpl.object2Json")
        return parseObject(input, clazz)
    }

    override fun <T : Any> parseObject(uuid: String, clazz: Type): T {
        log("LruCacheSerializationServiceImpl.parseObject")
        val obj = lruCache.get(uuid)
        lruCache.remove(uuid)
        return obj as T
    }
}